<template>
	<block>
		<view class="c-pload" :class="ggclass" v-if="type === 'image'">
			<view class="img-box" v-for="(v,i) in val" :key="i">
				<image class="img" :style="{borderRadius:radius,width,height,}" :src="v | imgFilter" @click="onImage">
				</image>
				<text class="iconfont icon-guanbi" @click="dele(v,i)"></text>
			</view>
			<view v-if="isUp" class="upload-button" @click="upload" :style="{borderRadius:radius,width,height}">
				<uni-icons type="plusempty" color="#ccc" :size="fontSize"></uni-icons>
			</view>
		</view>
		<view class="c-pload" :class="ggclass" v-else>
			<view class="img-box" v-for="(v,i) in val" :key="i">
				<video class="img" id="video" :style="{borderRadius:radius,width,height,}" :src="v | imgFilter"
					@click="onVideo" :controls="controls" @fullscreenchange="fullscreenchange" :muted="ismuted"
					:initial-time="0.01" :direction="0" :object-fit="objectFit">
				</video>
				<text class="iconfont icon-guanbi" @click="dele(v,i)"></text>
			</view>
			<view v-if="isUp" class="upload-button" @click="upload" :style="{borderRadius:radius,width,height}">
				<uni-icons type="plusempty" color="#ccc" :size="fontSize"></uni-icons>
			</view>
		</view>
	</block>

</template>

<script>
	import {
		defaultAvatar
	} from '../../static/img/base64.js'
	import {
		imgPreview
	} from '../ways/img.js'
	export default {
		name: 'c-upload',
		inject: {
			Cinput: {
				default: {}
			}
		},
		props: {
			type: {
				type: String,
				default: 'image'
			},
			maxCount: {
				type: Number,
				default: 1
			},
			ggclass: {
				type: String,
				default: ''
			},
			radius: {
				type: String,
				default: ''
			},
			width: {
				type: String,
				default: ''
			},
			height: {
				type: String,
				default: ''
			},
			value: {
				type: String,
				default: ''
			},
			api: {
				type: String,
				default: '/upload/image'
			},
			vapi: {
				type: String,
				default: '/upload/video'
			},
			isPreview: {
				type: Boolean,
				default: false
			},
			isUpload: {
				type: Boolean,
				default: false
			},
			videoSize: { //视频大小
				Number,
				default: 30
			},
			maxDuration: { //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
				Number,
				default: 10
			},
			range_key: {
				type: String,
				default: 'url'
			}
		},
		data() {
			return {
				// imgList: [],
				objectFit: "cover", //是否裁剪
				ismuted: true, //是否静音。
				isFullscreen: false, //是否全屏。
				val: [],
				videoContext: {},
				controls: false,
			}
		},
		watch: {
			value: {
				handler(n) {
					let imgurl = []
					if (!this.value) {

					} else if (Array.isArray(this.value)) {
						imgurl = this.value
					} else {
						imgurl = this.value.split(',')
					}
					this.val = new Proxy(imgurl, {
						get: (item, key) => {

							return item[key]
						},
						set: (item, key, value) => {
							item[key] = value
							if (Array.isArray(this.value)) {
								this.$emit('input', item)
								this.$emit('change', item)
							} else {
								this.$emit('input', item.join(','))
								this.$emit('change', item.join(','))
							}
							return true
						}
					})
					if (this.type === 'video') {
						this.$nextTick(() => {
							this.videoContext = uni.createVideoContext('video', this)
						})
					}
				},
				deep: true,
				immediate: true
			}
		},
		computed: {
			isUp() {
				if ((this.val.length < this.maxCount) && this.isUpload) {
					return true
				}
				return false
			},
			// val: {
			// 	get() {


			// 	},
			// 	set(val) {
			// 		// this.imgList = val
			// 		// console.log(val, '---')
			// 		// if (Array.isArray(this.value)) {
			// 		// 	this.$emit('input', val)
			// 		// 	this.$emit('change', val)
			// 		// } else {
			// 		// 	this.$emit('input', val.join(','))
			// 		// 	this.$emit('change', val.join(','))
			// 		// }
			// 	}
			// },
			fontSize() {
				return `${parseInt(this.width || '150') /2}rpx`
			},
		},
		methods: {
			dele(v, i) {
				this.val.splice(i, 1)
			},
			onImage(event) {
				if (this.isPreview) {
					imgPreview(this.valUrl)
				}
				this.$emit('click', event)
				this.$emit('tap', event)
			},
			fullscreenchange(e) {
				if (e.detail.fullScreen) {
					this.ismuted = false
					this.objectFit = "contain"
					this.isFullscreen = true
				} else {
					this.objectFit = "cover"
					this.ismuted = true
					this.isFullscreen = false
				}
			},
			onVideo() {
				if (this.isFullscreen) {
					this.videoContext.exitFullScreen()
					this.videoContext.stop()
				} else {
					this.videoContext.requestFullScreen()
					this.videoContext.play()
				}
			},
			async upload() {
				let result = null
				if (this.type === 'image') {
					result = await this.chooseImg()
				} else {
					result = await this.chooseVideo()
				}
				console.log(result, 'result')
				let pArr = []
				result.forEach(async v => {
					pArr.push(this.uploadFile(v.path))
				})
				let p = await Promise.all(pArr)
				this.val.push(...p)
				this.$nextTick(() => {
					typeof this.Cinput.verify === 'function' && this.Cinput.verify()
				})
			},
			async chooseImg() {
				let [err, res] = await uni.chooseImage({
					count: this.maxCount - this.val.length,
				})
				if (err) {
					uni.showToast({
						title: err.errMsg
					})
				}
				console.log(res, 'res')
				return res.tempFiles || []
			},
			chooseVideo() {
				return new Promise((resvole, inject) => {
					uni.chooseVideo({
						count: this.maxCount - this.val.length,
						compressed: true,
						maxDuration: this.maxDuration,
						success: async file => {
							if (file.size > this.videoSize * 1024 * 1000) {
								inject(false)
								return uni.showModal({
									title: '提示',
									content: `请上传${this.videoSize}M以内的视频`,
									showCancel: false
								});
							}
							// const tempFiles = file.tempFiles[0].tempFilePath;
							const tempFiles = file.tempFilePath;
							console.log(file, 'file')
							// uni.showToast({
							// 	title: '正在上传...',
							// 	icon: 'loading',
							// 	mask: true,
							// 	duration: 10000
							// });
							resvole([{
								...file,
								path: tempFiles
							}])
							// uni.uploadFile({
							// 	url: config.mallApiUrl + '/api/FilesApi/UploadFiles',
							// 	filePath: tempFiles,
							// 	name: 'file',
							// 	success: (res) => {
							// 		console.log(videoInfo, 'videoInfo')
							// 		this.$emit('videoInfo', JSON.stringify(videoInfo))
							// 		// this.videoObj.width = file.tempFiles[0].width + 'rpx'
							// 		// this.videoObj.height = file.tempFiles[0].height + 'rpx'
							// 		const data = JSON.parse(res.data);
							// 		// _this.videoUrl = config.mallApiUrl + data.result.webUrl;
							// 		this.videoUrl = data.result.webUrl;
							// 		this.$emit('input', this.videoUrl);
							// 		this.$forceUpdate();
							// 	},
							// 	complete() {
							// 		uni.hideToast();
							// 	}
							// });
						}
					});
				})

			},
			/**
			 * 上传文件
			 * @param {string} v 文件路径
			 * @param {string} size 文件大小
			 */
			uploadFile(filePath) {
				uni.showToast({
					title: '上传中...',
					icon: 'loading'
				})
				return new Promise(async (ress, err) => {
					let apiUrl = this.type === 'image' ? this.api : this.vapi
					if (!apiUrl.includes('http')) {
						apiUrl = this.$config.baseUrl + apiUrl
					}
					uni.uploadFile({
						url: apiUrl,
						filePath,
						name: 'file',
						success: (res) => {
							const data = JSON.parse(res.data);
							let url = data.result[this.range_key];
							ress(url)
						},
						fail(error) {
							err(error)
							console.log(error, 'error');
						},
						complete() {
							uni.hideToast();
						}
					});
				})
			}
		}

	}
</script>

<style lang="scss" scoped>
	.c-pload {
		width: 100%;
		// flex: 1;
		position: relative;
		display: inline-flex;
		flex-wrap: wrap;

		.img-box {
			position: relative;

			.img {
				width: 140rpx;
				height: 140rpx;
				margin-bottom: 10rpx;
				margin-right: 10rpx;
			}

			.icon-guanbi {
				position: absolute;
				top: 0;
				right: 10rpx;
				padding: 7rpx 10rpx;
				background: #666;
				color: #fff;
				font-size: 20rpx;
				border-radius: 0 10rpx 0 10rpx;
			}
		}

		.upload-button {
			margin-bottom: 10rpx;
			width: 140rpx;
			height: 140rpx;
			border-radius: 20rpx;
			background: #fff;
			display: inline-flex;
			justify-content: center;
			align-items: center;
			box-shadow: 1px 2px 7px 0px #ccc;
		}
	}
</style>